--drop table GOOGLECODERS.Postnet;
--drop table GOOGLECODERS.Postnet_x_Beneficiario
--drop table GOOGLECODERS.Postnet

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [GOOGLECODERS].[Postnet_x_Beneficiario](
	[IdPostnet] [int] NOT NULL,
	[IdBeneficiario] [int] NOT NULL,
	PRIMARY KEY([IdPostnet], IdBeneficiario)
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF

ALTER TABLE [GOOGLECODERS].[Postnet_x_Beneficiario] ADD
	CONSTRAINT FK_tPostnet FOREIGN KEY (IdPostnet)
		REFERENCES [GOOGLECODERS].[Postnet] (IdPostnet),
	CONSTRAINT FK_tBeneficiarios FOREIGN KEY (IdBeneficiario)
		REFERENCES [GOOGLECODERS].[Beneficiarios] (IdBeneficiario);
GO

INSERT INTO [GOOGLECODERS].[Postnet_x_Beneficiario]
			([IdPostnet]
			,[IdBeneficiario])
SELECT DISTINCT
	p.IdPostnet,
	b.IdBeneficiario
FROM [gd_eschema].[Maestra] m
INNER JOIN [GOOGLECODERS].[Postnet] P ON p.IdPostnet = m.[POSTNET_NRO_SERIE]
INNER JOIN [GOOGLECODERS].[Beneficiarios] b ON b.[RazonSocial] = m.[BENEFICIARIO_NOMBRE]